Einführung

Die Daten

Zuerst schauen wir uns nur eins der Jahre genauer an, und zwar nur für die Länder im Datensatz:

gapminder_dat <- gapminder_dat_full %>% 
  filter(time == "2020", !is.na(country)) 

RStudio Projekte

Hilft ungemein beim Organisieren von Dateien und Code!

Übung

Erstelle einen neuen Ordner (falls noch nicht getan) für diesen Workshop, und lege darin ein RStudio Projekt an (File - New Project).

Skripte

Hier kommt der Code rein!

Übung

Erstelle einen neuen Unterordner und lege darin ein R-Skript and (File - New File - R Script). In diesen kommen dann die Übungsaufgaben und Notizen aus dem Workshop. Leg am besten für jedes Thema ein eigenes Skript an, damit sie übersichtlich bleiben.

Einlesen von Daten

Data type Import Export
R objects (.Rdata, .rda) load() save()
single R object (.rds) readRDS() saveRDS()
text-files (.txt) read.table() write.table()
.csv-files (.csv) read.csv() write.csv()
Excel-files (.xlsx) readxl::read_excel() writexl::write_xlsx()
SPSS-files (.sav) haven::read_sav() haven::write_sav()
SAS-files (.sas) haven::read_sas() haven::write_sas()
Stata-files (.stata) haven::read_dta() haven::write_dta()

Schlecht:

setwd()

Besser:

Rstudio-Project + here

Bild von Alison Horst.

Bild von Alison Horst.

here-Paket

here ist ein Paket zum Erstellen von Dateipfaden. Dadurch können Probleme mit relativen und absoluten Pfaden vermieden werden.

C:\Users\hafiznij\Documents\GitHub\IRT_workshop\raw_data\athletes.rds wird zu:
here::here("raw_data", "athletes.rds").

Also:

# install.packages("here")
athletes <- readRDS(here::here("raw_data", "athletes.rds"))

Pakete

Pakete sind Erweiterungen zum base R und funktionieren ein bisschen wie Apps im Playstore:

  • Einmalig installieren:
install.packages("packagename")
  • Bei jeder Nutzung in die R-Session laden:
library(packagename)

Icons von icons8.de.

Foto von elnaz asadi auf Unsplash

tidyverse

https://upload.wikimedia.org/wikipedia/commons/f/ff/Tidyverse_hex_logo.png

Verbreitete Paketsammlung in R für so ziemlich jede Stufe der Datenauswertung. Der meiste Code den wird schreiben wird wahrscheinlich aus einer Mischung aus base R und tidyverse bestehen.

tidyverse: Pipe Operator

%>%

sum(seq(from = 1, to = mean(c(45:100), na.rm = TRUE), by = 0.1))
[1] 26313

wird zu:

library(tidyverse)

c(45:100) %>%
  mean(na.rm = TRUE) %>%
  seq(from = 1, to = ., by = 0.1) %>%
  sum
[1] 26313

Komplexes konditionales Subsetting

Diese Prinzip können wir uns zu Nutze machen, um mehrere Bedingungen zu verknüpfen:

gapminder_dat <- gapminder_dat_full[(gapminder_dat_full$name == "Germany") & (gapminder_dat_full$time > 1990 | gapminder_dat_full$pop > 70000000), ]
head(gapminder_dat)
     country time co2_cons co2_pcap_cons co2_pcap_terr  co2_terr
9951     deu 1938  610.411         8.582         8.407 597990567
9952     deu 1939  658.472         9.210         9.022 645084955
9953     deu 1940  664.244         9.259         9.071 650753358
9954     deu 1941  670.812         9.336         9.147 657186238
9955     deu 1942  678.009         9.439         9.248 664253692
9956     deu 1943  689.722         9.622         9.427 675721467
     cumulative_co2_emissions_tonnes      pop u5pop g77_and_oecd_countries
9951                     23542560629 70009837    NA                   oecd
9952                     24201032456 70374463    NA                   oecd
9953                     24865276755 70611563    NA                   oecd
9954                     25536089195 70720509    NA                   oecd
9955                     26214098342 70700669    NA                   oecd
9956                     26903819845 70551405    NA                   oecd
     income_groups is--country iso3166_1_alpha2 unicode_region_subtag
9951   high_income        TRUE               DE                    DE
9952   high_income        TRUE               DE                    DE
9953   high_income        TRUE               DE                    DE
9954   high_income        TRUE               DE                    DE
9955   high_income        TRUE               DE                    DE
9956   high_income        TRUE               DE                    DE
     iso3166_1_alpha3 iso3166_1_numeric iso3166_2 landlocked latitude longitude
9951              DEU               276      <NA>  coastline     51.5      10.5
9952              DEU               276      <NA>  coastline     51.5      10.5
9953              DEU               276      <NA>  coastline     51.5      10.5
9954              DEU               276      <NA>  coastline     51.5      10.5
9955              DEU               276      <NA>  coastline     51.5      10.5
9956              DEU               276      <NA>  coastline     51.5      10.5
     main_religion_2008    name un_state world_4region       world_6region
9951          christian Germany     TRUE        europe europe_central_asia
9952          christian Germany     TRUE        europe europe_central_asia
9953          christian Germany     TRUE        europe europe_central_asia
9954          christian Germany     TRUE        europe europe_central_asia
9955          christian Germany     TRUE        europe europe_central_asia
9956          christian Germany     TRUE        europe europe_central_asia
     unicef_region income_3groups                  un_sdg_region
9951           eca    high_income un_europe_and_northern_america
9952           eca    high_income un_europe_and_northern_america
9953           eca    high_income un_europe_and_northern_america
9954           eca    high_income un_europe_and_northern_america
9955           eca    high_income un_europe_and_northern_america
9956           eca    high_income un_europe_and_northern_america
                 un_sdg_ldc unhcr_region west_and_rest global
9951 un_not_least_developed unhcr_europe          west   <NA>
9952 un_not_least_developed unhcr_europe          west   <NA>
9953 un_not_least_developed unhcr_europe          west   <NA>
9954 un_not_least_developed unhcr_europe          west   <NA>
9955 un_not_least_developed unhcr_europe          west   <NA>
9956 un_not_least_developed unhcr_europe          west   <NA>

NA

Viele der Zeilen enthalten nur NA Werte. Das liegt daran, dass der Vergleich in einigen Zeilen nur auf NAs zugreifen kann, und dann einfach eine NA-Zeile ausgibt

Subsetting Zeilen: Tidyverse

library(tidyverse)

gapminder_dat_full %>%
  filter(name == "Germany", (gapminder_dat_full$time > 1990 | gapminder_dat_full$pop > 70000000)) %>%
  head
  country time co2_cons co2_pcap_cons co2_pcap_terr  co2_terr
1     deu 1938  610.411         8.582         8.407 597990567
2     deu 1939  658.472         9.210         9.022 645084955
3     deu 1940  664.244         9.259         9.071 650753358
4     deu 1941  670.812         9.336         9.147 657186238
5     deu 1942  678.009         9.439         9.248 664253692
6     deu 1943  689.722         9.622         9.427 675721467
  cumulative_co2_emissions_tonnes      pop u5pop g77_and_oecd_countries
1                     23542560629 70009837    NA                   oecd
2                     24201032456 70374463    NA                   oecd
3                     24865276755 70611563    NA                   oecd
4                     25536089195 70720509    NA                   oecd
5                     26214098342 70700669    NA                   oecd
6                     26903819845 70551405    NA                   oecd
  income_groups is--country iso3166_1_alpha2 unicode_region_subtag
1   high_income        TRUE               DE                    DE
2   high_income        TRUE               DE                    DE
3   high_income        TRUE               DE                    DE
4   high_income        TRUE               DE                    DE
5   high_income        TRUE               DE                    DE
6   high_income        TRUE               DE                    DE
  iso3166_1_alpha3 iso3166_1_numeric iso3166_2 landlocked latitude longitude
1              DEU               276      <NA>  coastline     51.5      10.5
2              DEU               276      <NA>  coastline     51.5      10.5
3              DEU               276      <NA>  coastline     51.5      10.5
4              DEU               276      <NA>  coastline     51.5      10.5
5              DEU               276      <NA>  coastline     51.5      10.5
6              DEU               276      <NA>  coastline     51.5      10.5
  main_religion_2008    name un_state world_4region       world_6region
1          christian Germany     TRUE        europe europe_central_asia
2          christian Germany     TRUE        europe europe_central_asia
3          christian Germany     TRUE        europe europe_central_asia
4          christian Germany     TRUE        europe europe_central_asia
5          christian Germany     TRUE        europe europe_central_asia
6          christian Germany     TRUE        europe europe_central_asia
  unicef_region income_3groups                  un_sdg_region
1           eca    high_income un_europe_and_northern_america
2           eca    high_income un_europe_and_northern_america
3           eca    high_income un_europe_and_northern_america
4           eca    high_income un_europe_and_northern_america
5           eca    high_income un_europe_and_northern_america
6           eca    high_income un_europe_and_northern_america
              un_sdg_ldc unhcr_region west_and_rest global
1 un_not_least_developed unhcr_europe          west   <NA>
2 un_not_least_developed unhcr_europe          west   <NA>
3 un_not_least_developed unhcr_europe          west   <NA>
4 un_not_least_developed unhcr_europe          west   <NA>
5 un_not_least_developed unhcr_europe          west   <NA>
6 un_not_least_developed unhcr_europe          west   <NA>

NA

Hier werden NA Werte automatisch ignoriert.

Subsetting Spalten: Tidyverse

gapminder_dat_full %>%
  select(name, time) %>%
  head
         name time
1 Afghanistan 1800
2 Afghanistan 1801
3 Afghanistan 1802
4 Afghanistan 1803
5 Afghanistan 1804
6 Afghanistan 1805

Faktoren

Wide-Format

inhabitants_wide <- data.frame(
  country = c("China", "India", "USA"),
  inhabitants_2021 = c(1425893465 , 1407563842, NA),
  inhabitants_2022 = c(1425857720, 1420939232, 338903174)
)

head(inhabitants_wide)
  country inhabitants_2021 inhabitants_2022
1   China       1425893465       1425857720
2   India       1407563842       1420939232
3     USA               NA        338903174

Long-Format

  country         variable      value
1   China             area    9597000
2   China inhabitants_2022 1425857720
3   India             area    3287000
4   India inhabitants_2022 1420939232
5     USA             area    9834000
6     USA inhabitants_2022  338903174

Von Wide zu Long

inhabitants_long_2 <- inhabitants_wide %>%
  pivot_longer(
    ## Spalten die gereshaped werden sollen
    cols = c("inhabitants_2022", "inhabitants_2021"),
    ## Neue Spalte, in der die bisherigen Spaltennamen gespeichert werden
    names_to = "year",
    ## Neue Spalte, in der die bisherigen Werte gespeichert werden
    values_to = "inhabitants"
  )

head(inhabitants_long_2)
# A tibble: 6 × 3
  country year             inhabitants
  <chr>   <chr>                  <dbl>
1 China   inhabitants_2022  1425857720
2 China   inhabitants_2021  1425893465
3 India   inhabitants_2022  1420939232
4 India   inhabitants_2021  1407563842
5 USA     inhabitants_2022   338903174
6 USA     inhabitants_2021          NA

Von Long zu Wide

inhabitants_wide_2 <- inhabitants_long %>%
  pivot_wider(
    id_cols = "country",
    names_from = "variable",
    values_from = "value"
  )

head(inhabitants_wide_2)
# A tibble: 3 × 3
  country    area inhabitants_2022
  <chr>     <dbl>            <dbl>
1 China   9597000       1425857720
2 India   3287000       1420939232
3 USA     9834000        338903174